﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace BaseUtilities
{
    public class ModelUtils
    {
        // Instant.
        private static ModelUtils _Instant;
        public static ModelUtils Instant
        {
            get 
            {
                if (_Instant == null)
                {
                    _Instant = new ModelUtils();
                }
                return _Instant; 
            }
            set { _Instant = value; }
        }
        
        
        //----------------------------------------
        public virtual void CopyValues(object pSource, object pDestination, bool pIsConverse)
        {
            Type tSource, tDestination;
            object oSource, oDestination;
            if (pIsConverse)
            {
                tSource = pDestination.GetType();
                tDestination = pSource.GetType();
                oSource = pDestination;
                oDestination = pSource;
            }
            else
            {
                tSource = pSource.GetType();
                tDestination = pDestination.GetType();
                oSource = pSource;
                oDestination = pDestination;
            }
            PropertyInfo[] tSourcePros = tSource.GetProperties();
            foreach (PropertyInfo item in tSourcePros)
            {
                PropertyInfo desPro = tDestination.GetProperty(item.Name);
                if (desPro != null)
                {
                    desPro.SetValue(oDestination, item.GetValue(oSource, null), null);
                }
            }
        }

        //----------------------------------------
        public virtual void CopyValues(object pSource, object pDestination, bool pIsConverse, params string[] pPropertyNames)
        {
            Type tSource, tDestination;
            object oSource, oDestination;
            if (pIsConverse)
            {
                tSource = pDestination.GetType();
                tDestination = pSource.GetType();
                oSource = pDestination;
                oDestination = pSource;
            }
            else
            {
                tSource = pSource.GetType();
                tDestination = pDestination.GetType();
                oSource = pSource;
                oDestination = pDestination;
            }
            foreach (string item in pPropertyNames)
            {
                PropertyInfo sourcePro = tSource.GetProperty(item);
                PropertyInfo desPro = tDestination.GetProperty(item);
                if (sourcePro != null && desPro != null)
                {
                    desPro.SetValue(oDestination, sourcePro.GetValue(oSource, null), null);
                }
            }
        }
    }
}
